<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="12">
        <el-card style="height: calc(100vh - 125px)">
          <div slot="header">
            <span><i class="el-icon-collection"></i> 分类列表({{ count }})</span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              icon="el-icon-refresh-right"
              @click="getTree()"
            ></el-button>
          </div>

          <el-input
            style="margin-bottom: 5px"
            clearable
            placeholder="输入关键字进行过滤"
            v-model="filterText"
          >
          </el-input>

          <div style="height: calc(100vh - 125px - 120px); overflow-x:scroll">
            <el-tree
              show-checkbox
              @check-change="checkChange"
              v-loading="loading"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              node-key="catId"
              class="filter-tree"
              :data="data"
              :props="defaultProps"
              @node-click="handleNodeClick"
              :filter-node-method="filterNode"
              :default-expanded-keys="expandedKeys"
              @node-expand="nodeExpand"
              @node-collapse="nodeCollapse"
              :auto-expand-parent="false"
              ref="tree"
              highlight-current
            >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>

        <span>
          <el-button
            type="text"
            size="mini"
            v-if="node.level < 3"
            @click.stop="() => append(data)"
          >
            添加
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click.stop="() => update(data)"
          >
            修改
          </el-button>
          <el-button
            type="text"
            size="mini"
            v-if="node.isLeaf"
            @click.stop="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card style="height: calc(100vh - 125px)">
          <div slot="header">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="appendRoot">添加一级节点</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="batchDelete" :disabled="batchDeleteFlag">
              批量删除
            </el-button>
          </div>
          <el-form ref="form" :model="detailForm" label-width="80px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="父节点">
                  <el-input v-model="detailForm.parentName" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="名称">
                  <el-input v-model="detailForm.name" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="图标地址">
                  <el-input v-model="detailForm.icon" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="计量单位">
                  <el-input v-model="detailForm.productUnit" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品数量">
                  <el-input v-model="detailForm.productCount" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序">
                  <el-input v-model="detailForm.sort" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="层级">
                  <el-input v-model="detailForm.catLevel" readonly/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>


    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item v-if="!form.catId && form.parentCid" label="父节点">
              <el-input v-model="form.parentName" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" clearable placeholder="请输入名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图标地址" prop="icon">
              <el-input v-model="form.icon" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="计量单位" prop="productUnit">
              <el-input v-model="form.productUnit" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品数量" prop="productCount">
              <el-input-number v-model="form.productCount" controls-position="right" :min="0" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="层级" prop="catLevel">
              <el-input v-model="form.catLevel" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Category',
  dicts: ['gl_show_status'],
  data() {
    return {
      loading: true,
      filterText: '',
      data: [],
      count: 0,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      expandedKeys: [],
      uri: '/product/category',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      detailForm: {},
      batchDeleteFlag: true
    }
  },
  created() {
    this.getTree()
  },
  methods: {
    handleNodeClick(data, node) {
      this.detailForm = data
      this.detailForm.parentName = node.parent.data.name
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    getTree() {
      this.loading = true
      this.$api.get(this.uri + '/tree').then(({ data }) => {
        this.data = data.data
        this.count = data.count
        this.loading = false
      })
    },
    append(data) {
      // const newChild = { id: id++, label: 'testtest', children: [] };
      // if (!data.children) {
      //   this.$set(data, 'children', []);
      // }
      // data.children.push(newChild);

      this.reset()
      this.form.parentCid = data.catId
      this.form.catLevel = data.catLevel + 1
      this.form.parentName = data.name
      this.open = true
      this.title = '添加'
    },
    appendRoot() {
      this.reset()
      this.form.catLevel = 1
      this.open = true
      this.title = '添加'
    },
    update(data) {
      // this.reset()
      // Object.assign(this.form, data)
      // this.form.children = undefined
      // this.open = true
      // this.title = "修改";

      this.reset()
      this.$api.get(this.uri + '/' + data.catId).then(resp => {
        this.form = resp.data
        this.open = true
        this.title = '修改'
      })
    },
    remove(node, data) {
      const id = data.catId
      this.$modal.confirm('是否确认删除' + data.name + '？').then(() => {
        return this.$api.delete(`${this.uri}/${id}`)
      }).then((resp) => {
        // const parent = node.parent;
        // const children = parent.data.children || parent.data;
        // const index = children.findIndex(d => d.id === data.id);
        // children.splice(index, 1);

        this.getTree()
        this.$modal.msgSuccess('删除成功')
      })
    },
    // 表单重置
    reset() {
      this.form = {
        catId: undefined,
        name: undefined,
        parentCid: undefined,
        parentName: undefined,
        catLevel: undefined,
        icon: undefined,
        productUnit: undefined,
        productCount: undefined,
        sort: 0,
      }
      this.resetForm('form')
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.catId != undefined) {
            this.$api.post(this.uri, this.form).then(resp => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getTree()
            })
          } else {
            this.$api.put(this.uri, this.form).then(resp => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getTree()
            })
          }
        }
      })
    },
    // 节点被勾选或取消勾选触发
    checkChange(data) {
      const keys = this.$refs.tree.getCheckedKeys()
      this.batchDeleteFlag = !keys.length
    },
    batchDelete() {
      // 获取选中节点的 cat_id 集合，如果某一父节点有其它子节点未选中，那么该父节点不会被获取
      const keys = this.$refs.tree.getCheckedKeys()
      if (keys.length) {
        this.$modal.confirm('是否确认删除选中的' + keys.length + '条数据？').then(() => {
          return this.$api.post(this.uri + '/batchDelete', keys)
        }).then((resp) => {
          this.getTree()
          this.$modal.msgSuccess('操作成功')
        })
      }
    },
    // 节点展开触发
    nodeExpand(data, node, self) {
      this.expandedKeys.push(data.catId)
    },
    // 节点关闭触发
    nodeCollapse(data, node, self) {
      this.expandedKeys = this.expandedKeys.filter(item => item !== data.catId)
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
